import { messages } from 'share/common';
import React from 'react';
import { connect } from 'react-redux';
import { Form, Input, Switch, Button, Icon, Select, message, Spin, Tooltip } from 'antd';
import config from 'config';
import httpFetch from 'share/httpFetch';
import contractService from 'containers/setting/contract-type-define/contract-type-define.service';
import SelectEmployeeGroup from 'components/template/select-employee-group';
import 'styles/receipt-type-setting/contract-type-define/new-contract-type.scss';
import PermissionsAllocation from 'components/template/permissions-allocation';

const FormItem = Form.Item;
const Option = Select.Option;

class NewContractType extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      fetching: false,
      isEnabled: true,
      setOfBooksOptions: [],
      contractCategory: [],
      data: {},
      formTypeOptions: [],
      radioValue: 'all',
      showSelectEmployeeGroup: false,
      chosenEmployeeIDs: [],
      editTag: false,
      //适用人员
      applyEmployee: 'BASIS_01',
      departmentOrUserGroupIdList: [],
      permissions: {
        type: 'all',
        values: []
      }
    };
  }

  componentWillMount() {
    if (this.props.main.tenantMode) { //集团模式
      httpFetch.get(`${config.baseUrl}/api/setOfBooks/by/tenant?roleType=TENANT`)
        .then((res) => { //账套
          this.setState({
            setOfBooksOptions: res.data
          });
        });
    } else { //公司模式
      httpFetch.get(`${config.baseUrl}/api/setOfBooks/query/dto`)
        .then((res) => { //账套
          this.setState({
            setOfBooksOptions: res.data
          });
        });
    }
    this.getSystemValueList(2202)
      .then(res => { //合同大类
        let contractCategory = res.data.values;
        this.setState({ contractCategory });
      });
  }

  componentWillReceiveProps(nextProps) {
    const applyEmployeeType = {
      'BASIS_01': 'all',
      'BASIS_02': 'department',
      'BASIS_03': 'group'
    };
    if (!nextProps.params.flag && this.props.params.flag) {
      // 关闭/新建
      this.props.form.resetFields();
      this.setState({
        data: {},
        applyEmployee: 'BASIS_01',
        permissions: {
          type: 'all',
          values: []
        }
      });
    }
    //编辑
    if (nextProps.params.flag && !this.props.params.flag && nextProps.params.record.id) {
      contractService.getContractTypeInfo(nextProps.params.setOfBooksId, nextProps.record.id)
        .then(res => {
          let temp = res.data;
          this.setState({
            data: temp,
            applyEmployee: temp.applyEmployee,
            departmentOrUserGroupIdList: res.data.departmentOrUserGroupIdList ? res.data.departmentOrUserGroupIdList : [],
            permissions: {
              type: applyEmployeeType[temp.applyEmployee],
              values: res.data.departmentOrUserGroupList ? res.data.departmentOrUserGroupList.map(item => {
                return {
                  label: item.pathOrName,
                  value: item.id,
                  key: item.id
                };
              }) : []
            }
          });
        });
    }
  }

  onFormFocus = () => {
    this.getFormType();
  };

  //获取关联表单类型
  getFormType = () => {
    this.setState({ fetching: true });
    let setOfBooksId = this.state.data.setOfBooksId || this.props.params.setOfBooksId;
    if (!setOfBooksId) {
      setOfBooksId = 0;
    }
    httpFetch.get(`${config.baseUrl}/api/custom/forms/loan/reference?setOfBooksId=${setOfBooksId}`)
      .then(res => {
        this.setState({ formTypeOptions: res.data, fetching: false });
      });
  };

  //状态改变
  switchChange = (status) => {
    this.setState({ isEnabled: status });
  };

  //修改适用人员
  onRadioChange = (e) => {
    this.setState({ radioValue: e.target.value });
  };

  handleSelectEmployeeCancel = () => {
    this.setState({ showSelectEmployeeGroup: false });
  };

  handleSelectEmployeeOk = (values) => {
    let IDs = [];
    values.checkedKeys.map(item => {
      IDs.push(item.value);
    });
    this.setState({ chosenEmployeeIDs: IDs });
    this.handleSelectEmployeeCancel();
  };

  //新建保存
  handleSave = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        values.isEnabled = this.state.isEnabled;
        this.state.formTypeOptions.map(item => {
          if (item.formOID === values.formOid) {
            values.formName = item.formName;
            values.formType = item.formType;
          }
        });

        //适用人员
        values.applyEmployee = this.state.applyEmployee;
        if (this.state.applyEmployee === 'BASIS_02' && !this.state.departmentOrUserGroupIdList.length) {
          message.warning(messages('adjust.departmentGroupIdList.warn' /*请至少选择一个部门*/));
          return;
        }
        if (this.state.applyEmployee === 'BASIS_03' && !this.state.departmentOrUserGroupIdList.length) {
          message.warning(messages('adjust.userGroupIdList.warn' /*请至少选择一个员工组*/));
          return;
        }
        delete values.departmentOrUserGroupIdList;
        values.departmentOrUserGroupIdList = this.state.applyEmployee === 'BASIS_01' ? [] : this.state.departmentOrUserGroupIdList;
        let params = [];
        params.push(values);
        this.setState({ loading: true });
        contractService.newContractType(values.setOfBooksId, params)
          .then(res => {
            if (res.status === 200) {
              this.setState({ loading: false });
              message.success(messages('common.save.success', { name: '' }));
              this.props.close(true);
            }
          })
          .catch(e => {
            this.setState({ loading: false });
            message.error(`${messages('common.save.filed')}，${e.response.data.message}`);
          });
      }
    });
  };

  //更新保存
  handleUpdate = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        values.isEnabled = this.state.isEnabled;
        values.id = this.state.data.id;
        values.versionNumber = this.state.data.versionNumber;
        values.isDeleted = false;
        values.createdBy = this.state.data.createdBy;
        this.state.formTypeOptions.map(item => {
          if (item.formOID === values.formOid) {
            values.formName = item.formName;
            values.formType = item.formType;
          }
        });
        //适用人员
        values.applyEmployee = this.state.applyEmployee;
        if (this.state.applyEmployee === 'BASIS_02' && !this.state.departmentOrUserGroupIdList.length) {
          message.warning(messages('adjust.departmentGroupIdList.warn' /*请至少选择一个部门*/));
          return;
        }
        if (this.state.applyEmployee === 'BASIS_03' && !this.state.departmentOrUserGroupIdList.length) {
          message.warning(messages('adjust.userGroupIdList.warn' /*请至少选择一个员工组*/));
          return;
        }
        delete values.departmentOrUserGroupIdList;
        values.departmentOrUserGroupIdList = this.state.applyEmployee === 'BASIS_01' ? [] : this.state.departmentOrUserGroupIdList;

        let params = [];
        params.push(values);
        this.setState({ loading: true });
        contractService.updateContractType(values.setOfBooksId, params)
          .then(res => {
            if (res.status === 200) {
              this.setState({ loading: false });
              message.success(messages('common.save.success', { name: '' }));
              this.props.close(true);
            }
          })
          .catch(e => {
            this.setState({ loading: false });
            message.error(`${messages('common.save.filed')}，${e.response.data.message}`);
          });
      }
    });
  };

  //选择人员或者员工组使用公共组件，监听onChange事件
  onPermissionChange = (values) => {
    let nowApplyEmployee = '';
    let nowDepartOrUserIdList = [];
    if (values.type === 'all') {
      nowApplyEmployee = 'BASIS_01';
    } else if (values.type === 'department') {
      nowApplyEmployee = 'BASIS_02';
    } else if (values.type === 'group') {
      nowApplyEmployee = 'BASIS_03';
    }
    values.values.map(value => {
      nowDepartOrUserIdList.push(value['value']);
    });
    this.setState({
      applyEmployee: nowApplyEmployee,
      departmentOrUserGroupIdList: nowDepartOrUserIdList
    });
  };
  //取消
  handleCancel = () => {
    this.props.form.resetFields();
    this.props.close();
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { loading, setOfBooksOptions, contractCategory, permissions, data, formTypeOptions, fetching, showSelectEmployeeGroup, chosenEmployeeIDs } = this.state;
    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 10, offset: 1 }
    };
    const form_label = (
      <span>
        {messages('adjust.formName' /**关联表单类型*/)}
        <Tooltip title={messages('contract.re.tips')} overlayStyle={{ width: 220 }}>
          <Icon type="info-circle-o" style={{ margin: '0 3px' }}/>
        </Tooltip>
      </span>
    );
    return (
      <div className="new-contract-type">
        <div className="common-item-title">{messages('pre.payment.essential.information')/*基本信息*/}</div>
        <Form onSubmit={data.id ? this.handleUpdate : this.handleSave}>
          <FormItem {...formItemLayout} label={messages('adjust.setOfBooks')}>
            {getFieldDecorator('setOfBooksId', {
              rules: [{
                required: true,
                message: messages('common.please.select')
              }],
              initialValue: data.setOfBooksId || this.props.params.setOfBooksId
            })(
              <Select disabled>
                {setOfBooksOptions.map((option) => {
                  return <Option
                    key={this.props.main.tenantMode ? option.id : option.setOfBooksId}>{option.setOfBooksCode} - {option.setOfBooksName}</Option>;
                })}
              </Select>
            )}
          </FormItem>

          <FormItem {...formItemLayout} label={messages('my.contract.category')}>
            {getFieldDecorator('contractCategory', {
              rules: [{
                required: true,
                message: messages('common.please.select')
              }],
              initialValue: data.contractCategory
            })(
              <Select placeholder={messages('common.please.select')} disabled={!!data.id}>
                {contractCategory.map((option) => {
                  return <Option key={option.value}>{option.messageKey}</Option>;
                })}
              </Select>
            )}
          </FormItem>

          <FormItem {...formItemLayout} label={messages('contract.type.code')}>
            {getFieldDecorator('contractTypeCode', {
              rules: [{
                required: true,
                message: messages('common.please.select')
              }],
              initialValue: data.contractTypeCode
            })(
              <Input placeholder={messages('common.please.select')} disabled={!!data.id}/>
            )}
          </FormItem>

          <FormItem {...formItemLayout} label={messages('contract.type.name')}>
            {getFieldDecorator('contractTypeName', {
              rules: [{
                required: true,
                message: messages('common.please.select')
              }],
              initialValue: data.contractTypeName
            })(
              <Input placeholder={messages('common.please.select')}/>
            )}
          </FormItem>

          {/*<FormItem {...formItemLayout} label={form_label}>*/}
          {/*  {getFieldDecorator('formOid', {*/}
          {/*    initialValue: data.formOid*/}
          {/*  })(*/}
          {/*    <Select allowClear onFocus={this.onFormFocus} placeholder={messages('common.please.select')} notFoundContent={fetching ?*/}
          {/*      <Spin size="small"/> : messages('my.contract.no.result')}>*/}
          {/*      {formTypeOptions.map(option => {*/}
          {/*        return <Option key={option.formOID}>{option.formName}</Option>;*/}
          {/*      })}*/}
          {/*    </Select>*/}
          {/*  )}*/}
          {/*</FormItem>*/}

          <FormItem {...formItemLayout} label={messages('common.column.status')}>
            {getFieldDecorator('isEnabled', {
              valuePropName: 'checked',
              initialValue: !data.id ? true : data.isEnabled
            })(
              <Switch checkedChildren={<Icon type="check"/>} unCheckedChildren={<Icon type="cross"/>} onChange={this.switchChange}/>
            )}
          </FormItem>

          <div className="common-item-title">{messages('adjust.authority.set' /*付款方式类型*/)}</div>
          <FormItem {...formItemLayout} label={messages('adjust.applicable.personnel')/*适用人员*/}>
            {getFieldDecorator('departmentOrUserGroupIdList', {
              initialValue: permissions
            })
            (
              <PermissionsAllocation params={{ setOfBooksId: data.setOfBooksId }} onChange={this.onPermissionChange}/>
            )}
          </FormItem>
          <div className="slide-footer">
            <Button type="primary" htmlType="submit" loading={loading}>{messages('common.save')}</Button>
            <Button onClick={this.handleCancel}>{messages('common.cancel')}</Button>
          </div>
        </Form>
        <SelectEmployeeGroup visible={showSelectEmployeeGroup}
                             onCancel={this.handleSelectEmployeeCancel}
                             onOk={this.handleSelectEmployeeOk}
                             selectedData={chosenEmployeeIDs}/>
      </div>
    );
  }
}

NewContractType.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    main: state.main
  };
}

const wrappedNewContractType = Form.create()(NewContractType);

export default connect(mapStateToProps, null, null, { withRef: true })(wrappedNewContractType);
